package com.betterwood.dragon.controllers;

import com.betterwood.dragon.core.common.JsonResult;
import com.betterwood.dragon.core.wx.WxAppidConfig;

import com.betterwood.dragon.service.UserService;
import com.betterwood.dragon.utils.HttpClientUtil;
import com.betterwood.dragon.utils.WxCheckSignatureUtils;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhengyanhua
 * @create 2021-03-18 14:09
 */
@RestController
@RequestMapping(value = "/wxuser")
@Api(tags = "微信小程序用户登录")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping(value = "/getAll")
    public JsonResult findAll() {
        return JsonResult.success(userService.findAll());
    }

    @ApiOperation(value = "根据小程序openid获取用户信息")
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public JsonResult find(String minappOpenId) {
        if (StringUtils.isBlank(minappOpenId)) {
            return JsonResult.fail("参数不能为空");
        }
        return JsonResult.success(userService.findByMinAppOpenId(minappOpenId));
    }

    private String getsessionkey(String code) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", WxAppidConfig.WX_LOGIN_APPID);
        params.put("js_code", code);
        params.put("grant_type", WxAppidConfig.WX_LOGIN_GRANT_TYPE);
        params.put("secret", WxAppidConfig.WX_LOGIN_SECRET);
        return HttpClientUtil.doGet(WxAppidConfig.WX_LOGIN_URL, params);
    }

    @GetMapping("/checktoken")
    public String checkToken(HttpServletRequest request, HttpServletResponse response) throws Exception {

        request.setCharacterEncoding("UTF-8");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        // log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature,
        // timestamp, nonce, echostr);
        return WxCheckSignatureUtils.checkSignature(signature, timestamp, nonce) ? echostr : null;
    }

    @PostMapping("/checktoken")
    public String PostToken(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr) throws Exception {
        // log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature,
        // timestamp, nonce, echostr);
        return WxCheckSignatureUtils.checkSignature(signature, timestamp, nonce) ? echostr : null;
    }
}
